package com.netease.cloud.cm.retrofit.logger;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.stream.Collectors;

@Slf4j
public class OkHttpLogger implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        //chain里面包含了request和response
        Request request = chain.request();

        long t1 = System.currentTimeMillis();
        Response response = chain.proceed(request);
        //收到响应的时间
        long t2 = System.currentTimeMillis();

        String curl = String.format("curl -X %s '%s' %s ", request.method(), request.url(), getHeader(request.headers()));
        //获取requestBody
        String requestString = null;
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            requestString = buffer.readUtf8();
            curl += String.format("-d '%s' ", requestString);
        }

        //获取responseBody
        ResponseBody responseBody = response.peekBody(1024 * 1024);
        log.info(response.code() + " " + (t2 - t1) + "ms" + " " + curl);
        log.debug("headers: " + request.headers().toString().trim().replace("\n", ", "));
        if (requestString != null){
            log.info("body: " + requestString);
        }

        log.info("response: " + responseBody.string());
        return response;
    }

    private String getHeader(Headers headers) {
        return headers.names().stream()
                      .map(name -> String.format("-H '%s: %s'", name, headers.values(name).get(0)))
                      .collect(Collectors.joining(" "));
    }
}